package nuffzone;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import com.google.appengine.api.users.User;


public class categoriesManager {
	
	private Map<User, ArrayList<String>> categoryListByUser;
	private static final categoriesManager instance = new categoriesManager();
	
	
	private categoriesManager(){
		this.categoryListByUser = new HashMap<User, ArrayList<String>>();
	}

	public static categoriesManager getInstance(){
		return instance;
	}
	
	public ArrayList<String> getCategoriesOfUser(User user){
		if(categoryListByUser.keySet().contains(user)){
			ArrayList<String> categories = categoryListByUser.get(user);
			Collections.sort(categories);
			return categories;
		}
		else return new ArrayList<String>();
	}
	
	public int addCategoryForUser(User user, String category){
		if(categoryListByUser.containsKey(user)){
			ArrayList<String> cList = categoryListByUser.get(user);
			if(!userHasCategory(user, category)){
				addAlphabetically(cList, category);
				categoryListByUser.put(user,cList);
			}
			else{
				return -1;
			}
		}
		else{
			ArrayList<String> cList = new ArrayList<String>();
			cList.add(category);
			categoryListByUser.put(user,cList);
		}
		return 1;
	}

	public int removeCategoryForUser(User user, String category) {
		if (userHasCategory(user, category)) {
			ArrayList<String> cList = categoryListByUser.get(user);
			cList.remove(category);
			return 1;
		}
		else{
			return -1;
		}
	}

	public boolean userHasCategory(User user, String category){
		boolean result = false;
		if(categoryListByUser.containsKey(user)){
			ArrayList<String> cList = categoryListByUser.get(user);
			ArrayList<String> trimmedCList = new ArrayList<String>();
			for(String c:cList){
				trimmedCList.add(c.toLowerCase());
			}
			if(trimmedCList.contains(category.toLowerCase())){
				result=true;
			}
		}
		return result;
	}
	
	private void addAlphabetically(ArrayList<String> cList, String category) {
		int i = 0;
		boolean inserted = false;
		while(i<(cList.size())&&!inserted){
			String cat = cList.get(i);
			if(comesBeforeAlphabetically(category,cat)){
				cList.add(i, category);
				inserted=true;
			}
			i++;
		}
		if(!inserted){
			cList.add(category);
		}
		
	}
	
	private boolean comesBeforeAlphabetically(String category, String cat) {
		boolean result = false;
		if(category.compareToIgnoreCase(cat)<=0){
			result=true;
		}
		return result;
	}

}